<?php

namespace App\Http\Controllers\Webdisk\Admin;

use App\Http\Controllers\Controller;
use App\Webdisk\Model\LogInfo;
use App\Webdisk\Model\StatInfo;
use App\Webdisk\Utils\SysInfo;
use Illuminate\Http\Request;

use function App\Webdisk\getDiskInfo;
use function App\Webdisk\makeRes;

class SystemController extends Controller
{
    function getLog(){
        $primary_data = LogInfo::orderBy('id','desc')->paginate()->toArray();
        $res = makeRes(1,$primary_data['data']);
        $res['total'] = $primary_data['total'];
        $res['last_page'] = $primary_data['last_page'];
        return $res;
    }
    //
    function getSystemInfo(){
        $res = [];
        // CPU信息
        $res['cpu_info']['core_count'] = (int)exec('cat /proc/cpuinfo | grep "core id" | sort -n | uniq | wc -l');
        $res['cpu_info']['thread_count'] = (int)exec('cat /proc/cpuinfo | grep processor | wc -l');
        $res['cpu_info']['name'] = exec('cat /proc/cpuinfo | grep name | uniq | awk -F \': \' \'{print $2}\'');
        exec('cat /proc/cpuinfo | grep MHz | awk \'{print $4}\'',$output);
        $res['cpu_info']['frequency'] = json_decode('['.implode(',',$output).']');
        unset($output);
        //硬盘信息
        exec("lsblk -Jb",$output);
        $t = json_decode(implode('',$output),true);
        $res['disk_info'] = [];
        for ($i=0; $i < count($t['blockdevices']); $i++) {
            $res['disk_info'][]= [
                'device'=>'/dev/'.$t['blockdevices'][$i]['name'],
                'partitions'=>getDiskInfo("/dev/{$t['blockdevices'][$i]['name']}")
            ];
        }

        //内存信息
        $res['memory_info'] = json_decode(exec('free -b | grep Mem | awk \'{ printf("{\"total\":%d,\"used\":%d,\"free\":%d,\"shared\":%d,\"buff_cache\":%d,\"available\":%d}", $2, $3, $4, $5, $6,$7) }\''));
        $res['swap_info'] = json_decode(exec('free -b | grep Swap | awk \'{ printf("{\"total\":%d,\"used\":%d,\"free\":%d}", $2, $3, $4) }\''));

        $res['resource_info'] = [
            'last_update_cache' => StatInfo::getInt('last_update_cache'),
            'cache_stat'=>StatInfo::get("cache_stat"),
            'file_count' => StatInfo::getInt('file_count'),
            'dir_count' => StatInfo::getInt('dir_count'),
            'total_file_size' => StatInfo::getInt('total_file_size')
        ];

        $res['net_info'] = SysInfo::getNetworkInterfacesInfo();
        $res['run_time'] = (int)exec('cat /proc/uptime | awk \'{print $1}\'');
        return makeRes(1,$res);
    }
}

